#include <iostream>
#include <ctime>
#include <unistd.h>
#include "block_queue.hpp"
#include "Task.hpp"

void *Consumer(void *args)
{
    BlockQueue<Task> *c = static_cast<BlockQueue<Task> *>(args);
    while (true)
    {
        Task t;
        c->Pop(&t);
        std::cout << t.result() << std::endl;
        // int out = 0;
        // c->Pop(&out);
        // std::cout << "Consumer pop ->" << out << std::endl;
        sleep(1);
    }
}

void *Productor(void *args)
{
    srand(time(nullptr) ^ getpid());
    BlockQueue<Task> *p = static_cast<BlockQueue<Task> *>(args);
    while (true)
    {
        int x = rand() % 100 + 1;
        int y = rand() % 10 + 1;
        Task t(x, y);

        p->Push(t);
        printf("productor push Task(x+y)->%d + %d\n", x, y);

        // int in = rand() % 10 + 1;
        // p->Push(in);
        // std::cout << "productor push ->" << in << std::endl;
        sleep(1);
    }
}

int main()
{
    BlockQueue<int> *bq = new BlockQueue<int>();

    pthread_t c1, c2, c3, p1, p2;
    pthread_create(&c1, nullptr, Consumer, bq);
    pthread_create(&c2, nullptr, Consumer, bq);
    pthread_create(&c3, nullptr, Consumer, bq);
    pthread_create(&p1, nullptr, Productor, bq);
    pthread_create(&p2, nullptr, Productor, bq);

    pthread_join(c1, nullptr);
    pthread_join(c2, nullptr);
    pthread_join(c3, nullptr);
    pthread_join(p1, nullptr);
    pthread_join(p2, nullptr);

    return 0;
}